package com.hzit.mmcb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzit.common.exception.Assert;
import com.hzit.common.result.PageResult;
import com.hzit.common.result.ResponseEnum;
import com.hzit.mmcb.core.enums.BorrowerStatusEnum;
import com.hzit.mmcb.core.enums.IntegralEnum;
import com.hzit.mmcb.core.enums.UserBindEnum;
import com.hzit.mmcb.core.pojo.dto.BorrowerAttachDTO;
import com.hzit.mmcb.core.pojo.dto.BorrowerDetailDTO;
import com.hzit.mmcb.core.pojo.entity.*;
import com.hzit.mmcb.core.mapper.BorrowerMapper;
import com.hzit.mmcb.core.pojo.vo.BorrowerApprovalVO;
import com.hzit.mmcb.core.pojo.vo.BorrowerVO;
import com.hzit.mmcb.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sound.sampled.Line;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2024-08-27
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BorrowerAttachService borrowerAttachService;

    @Autowired
    private DictService dictService;
    @Autowired
    private UserIntegralService userIntegralService;
    @Autowired
    private IntegralGradeService integralGradeService;

    @Override
    public void saveBorrowerVOByUserId(BorrowerVO vo, Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(vo,borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setMobile(userInfo.getMobile());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        this.baseMapper.insert(borrower);
        List<BorrowerAttach> borrowerAttachList = vo.getBorrowerAttachList();
        borrowerAttachList.forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttachService.save(borrowerAttach);
        });

        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoService.updateById(userInfo);
    }

    @Override
    public Integer getStatus(Long userId) {
        List<Object> objects = this.baseMapper.selectObjs(new LambdaQueryWrapper<Borrower>().select(Borrower::getStatus).eq(Borrower::getUserId, userId));
        if (objects.size()==0){
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }

        return (Integer) objects.get(0);
    }

    @Override
    public PageResult<Borrower> listPage(Integer page, Integer limit, String keyword) {
        LambdaQueryWrapper<Borrower> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Borrower::getMobile,keyword)
                .or().like(Borrower::getName,keyword)
                .or().like(Borrower::getIdCard,keyword);
        Page<Borrower> page1 = this.page(new Page<>(page, limit), lambdaQueryWrapper);
        return new PageResult<>(page1.getTotal(),page1.getRecords());
    }

    /**
     * 根据id获取借款人审批信息
     * @param id
     * @return
     */
    @Override
    public BorrowerDetailDTO getDetailById(Integer id) {
        Borrower borrower = this.getById(id);
        BorrowerDetailDTO borrowerDetailDTO=new BorrowerDetailDTO();
        BeanUtils.copyProperties(borrower,borrowerDetailDTO);
        //设置学历
        String education=getDictName(borrower.getEducation(),"education");
        borrowerDetailDTO.setEducation(education);
        //设置收入
        String income = getDictName(borrower.getIncome(), "income");
        borrowerDetailDTO.setIncome(income);
        //设置工作
        String industry = getDictName(borrower.getIndustry(), "industry");
        borrowerDetailDTO.setIndustry(industry);
        //设置还款来源
        String returnSource = getDictName(borrower.getReturnSource(), "returnSource");
        borrowerDetailDTO.setReturnSource(returnSource);
        //设置联系人关系
        String relation = getDictName(borrower.getContactsRelation(), "relation");
        borrowerDetailDTO.setContactsRelation(relation);
        borrowerDetailDTO.setSex(borrower.getSex()==1?"男":"女");
        borrowerDetailDTO.setMarry(borrower.getMarry()?"已婚":"未婚");
        borrowerDetailDTO.setStatus(BorrowerStatusEnum.getMsgByStatus(borrower.getStatus()));
        //查询材料
        List<BorrowerAttachDTO> borrowerAttachDTOList=borrowerAttachService.getborrowerAttachDTOList(id);
        borrowerDetailDTO.setBorrowerAttachDTOList(borrowerAttachDTOList);
        return borrowerDetailDTO;
    }

    /**
     * 进行审批
     * @param borrowerApprovalVO
     */
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        //设置状态
        Long borrowerId = borrowerApprovalVO.getBorrowerId();
        Borrower borrower = this.getById(borrowerId);
        borrower.setStatus(borrowerApprovalVO.getStatus());
        this.updateById(borrower);
        if (borrowerApprovalVO.getStatus()==-1){
            return;
        }
        //设置积分
        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);

        UserIntegral userIntegral=new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(borrowerApprovalVO.getInfoIntegral());
        userIntegral.setContent("基础积分");
        userIntegralService.save(userIntegral);
        int curIntegral = userInfo.getIntegral() + borrowerApprovalVO.getInfoIntegral();
        //身份证信息
        if (borrowerApprovalVO.getIsIdCardOk()){
            curIntegral += IntegralEnum.BORROWER_IDCARD.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegralService.save(userIntegral);
        }
        //房产信息
        if(borrowerApprovalVO.getIsHouseOk()) {
            curIntegral += IntegralEnum.BORROWER_HOUSE.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral()
            );
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegralService.save(userIntegral);
        }
        //车辆信息
        if(borrowerApprovalVO.getIsCarOk()) {
            curIntegral += IntegralEnum.BORROWER_CAR.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegralService.save(userIntegral);
        }
        userInfo.setIntegral(curIntegral);
        //修改审核状态
        userInfo.setBorrowAuthStatus(borrowerApprovalVO.getStatus());
        userInfoService.updateById(userInfo);

    }

    /**
     * 获取贷款金额上线
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        Assert.isTrue(userInfo.getBindStatus()!= UserBindEnum.NO_BIND.getStatus(), ResponseEnum.USER_NO_BIND_ERROR);
        Assert.isTrue(userInfo.getBorrowAuthStatus()!= BorrowerStatusEnum.NO_AUTH.getStatus(),ResponseEnum.USER_NO_AMOUNT_ERROR);
        Integer integral = userInfo.getIntegral();
        LambdaQueryWrapper<IntegralGrade> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(IntegralGrade::getIntegralEnd,integral)
                .le(IntegralGrade::getIntegralStart,integral);
        IntegralGrade integralGradeServiceOne = integralGradeService.getOne(lambdaQueryWrapper);
        return integralGradeServiceOne.getBorrowAmount();
    }

    /**
     * 获取字典中的名称
     * @param value
     * @param dictCode
     * @return
     */
    public String getDictName(Integer value, String dictCode) {
        Dict dictServiceOne = dictService.getOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
        Dict dict = dictService.getOne(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getParentId, dictServiceOne.getId())
                .eq(Dict::getValue, value));
        return dict.getName();
    }
}
